# Code for Table L1: OLS

rm(list = ls())

## ---------------------------------------
## Load Packages 
## ---------------------------------------

require('AER')
require('ivpack')
require('data.table')

## ---------------------------------------
## Load Data and Functions
## ---------------------------------------
load("../data0812.RData")

directory <- "../functions/"
functions <- list.files(directory)  
loadfunctions <- sapply(functions, FUN = function(x)source(paste0(directory, x)))

## ---------------------------------------
#  Select Last Case Before Election
## ---------------------------------------
data0812 <- lastCase(data0812)

## ---------------------------------------
## OLS
## ---------------------------------------
time.controls <- "as.factor(court_time1) + as.factor(court_time2) + as.factor(court_dow) + as.factor(court_shift) + as.factor(totOGS2)"
case.controls <-   "as.factor(any_drug_2) +  as.factor(any_violent_2) + as.factor(fire_arms_2) +  as.factor(any_rob_2) + as.factor(any_dui_2) + as.factor(prior_offender_2)"
demo.controls <- "age_2012 + I(age_2012^2) + Female + as.factor(race) + vote2008 + as.factor(noteli08) + regis_before"
 
outc.1 <- "vote2012"
endo.1 <- "pti"
inst.1 <- "judgeiv"

form.01 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls))
form.02 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls))
form.03 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls, "+", case.controls))

m0a1 <- ivreg(form.01, data = data0812)
m0a2 <- ivreg(form.02, data = data0812)
m0a3 <- ivreg(form.03, data = data0812)


cont <- data.table(round(rbind(c(robust.se(m0a1)[2, c(1:2,4)], robust.se(m0a2)[2, c(1:2,4)], robust.se(m0a3)[2, c(1:2,4)]),
                               c(m0a1$n, NA, NA, m0a2$n, NA, NA, m0a2$n, NA, NA) ), 3))

cat("\nPrinting Table L1: OLS results...\n")
print(cont)
